<?php

namespace Common\Commission;

use Think\Log;

class NormalAdapter {

    public $_error = "";

//
     
    /*
     * 检测参数有效性   
     * $commission_level 分销层数
     * string $commission_scale 分销比例 18|12|5
     * @autho xingji
     */
    public function assign($order_no, $commission_level = 0, $commission_scale = "", $assign_scale = 100) {

        if (empty($order_no)) {
            $this->_error = "没有订单号";
            return false;
        }

        if (is_string($commission_scale)) {
            $commission_scale = explode("|", $commission_scale);
        }

        if (!is_array($commission_scale)) {
            $this->_error = "佣金分配参数不正确";
            return false;
        }

        return $this->commission($order_no, $commission_level, $commission_scale, $assign_scale);
    }

    /*
     * 计算三级分销佣金
     * array $commission_scale
     * @根据pv值分佣
     */

    private function commission($order_no, $commission_level, $commission_scale, $assign_scale) {

        $order_model = D('Order');
        //查找订单是否存在
        $omap = array(
            'order_no' => $order_no,
            'pay_status' => 2,
            'status' => 1
        );
        $order = $order_model->where($omap)->find();

        if (empty($order)) {
            $this->_error = ("订单编号:" . $order_no . "，分佣失败，订单信息不存在");
            return false;
        }

        $member_model = D("Member");

        //查找订单用户是否存在
        $current_member = $member_model->find($order['user_id']);


        if (empty($current_member)) {
            $this->_error = ("订单编号:" . $order_no . "，分佣失败，订单用户不存在");
            return false;
        }

        //判段订单用户是否是顶级用户
        if ($current_member['id'] == $current_member['flag']) {
            $this->_error = ("订单编号:" . $order_no . "，分佣失败，这个用户没有推荐人");
            return false;
        }

        $top_member = $member_model->find($current_member['flag']);
        if (empty($top_member)) {
            $this->_error = ("订单编号:" . $order_no . "，分佣失败,没有查找到团队顶级用户");
            return false;
        }

        $ordergoods_model = D('OrderGoods');

        //查找订单商品信息
        $ogmap = array(
            'order_id' => $order['id'],
            'order_no' => $order['order_no']
        );

        $order_goods = $ordergoods_model->where($ogmap)->select();
        if (empty($order_goods)) {
            $this->_error = ("订单编号:" . $order_no . "，分佣失败，订单商品查询失败!");
            return false;
        }

        //统计订单用户的所有上级
        $tmap["lft"] = array('between', array($top_member['lft'], $current_member['lft']));
        $tmap["rgt"] = array('between', array($current_member['rgt'], $top_member['rgt']));
        $tmap["id"] = array('neq', $current_member['id']);
        $tmap["flag"] = array('eq', $current_member['flag']);
        $tree_users = $member_model->where($tmap)->order("lft desc")->select(); //倒序排列
 
        $commission_list = array();  //佣金列表
        $pids = array();  //产品ID
        $cmd = array();
        //把商品一条条的按分销层数返佣

        foreach ($order_goods as $goods) {

            if ($goods["commission_status"] == 1) {
                $this->_error = ("订单编号:" . $order_no . "订单商品已经计算分佣");
                return false;
            }

            /* $commission_total = $goods['pv'] * $goods['count'] * ($assign_scale / 100); //根据pv值计算分佣
              $commission_total_fact = $goods['pv'] * $goods['count']; */

            $commission_total = $goods['price'] * $goods['count'] * ($assign_scale / 100); //根据售价计算分佣
            $commission_total_fact = $goods['price'] * $goods['count'];


            $pids[] = $goods['goods_id'];
            $tmp = '';
            //根据平台设置的分佣等级处理分佣信息
            for ($index = 0; $index < $commission_level; $index++) {

                $scale = 0;  //默认为0不分佣
                // array $commission_scale 18|12|5
                if (isset($commission_scale[$index])) {
                    //当前级数的分佣比例
                    $scale = $commission_scale[$index];
                }

                //该商品的分佣金额 C('FX_USER_DISCOUNT') / 10
                $commission = $commission_total_fact * ($scale / 100);
                $cm = NULL;
             

                //倒序排列，0表示直推介绍人人
                if (isset($tree_users[$index])) {
                    $res = $member_model->checkIdentity($tree_users[$index]['total_spend'], $index, $current_member['total_spend'], $current_member['id'],$tree_users[$index]['id'] );
                    if ($res == 1) {
                        $cm = $tree_users[$index];
                          $cmd[]=$cm;

                    } elseif (($res == 2) && $index == 0) {
                        $cm = $tree_users[0]; //799支付会员只返利一级      
                         $cmd[]=$cm;
                        $commission = $member_model->returnMaxLvlMoney($commission_total_fact);
                   } else {
                        continue;
                    }
                } else {
                    break;
                }
                if (!empty($cm['id'])) {
                    $commission_list[] = array(
                        "user_id" => $cm['id'],
                        "customer_id" => $order['user_id'],
                        "lvl_num" => $index + 1, //消费者是会员的几级会员
                        "order_no" => $order['order_no'],
                        "commission" => $commission,
                        "commission_total" => $commission_total,
                        "commission_total_fact" => $commission_total_fact,
                        "commission_scale" => $scale,
                        "assign_scale" => $assign_scale,
                        "goods_id" => $goods['goods_id'],
                        "status" => 1,
                        "create_time" => NOW_TIME,
                        "update_time" => NOW_TIME
                    );
                }
            }
        }
   
        //普通会员消费额到799之后，升级成799会员

        $current_member['total_spend'] >= 799 ? $member_model->where("id =" . $order['user_id'])->save(array("max_lvl" => 1)) : true;

        $membercom_model = D('MemberCommission');

        Log::write('分佣数据:' . json_encode($commission_list));

        if (count($commission_list) > 0) {

            $rows = $membercom_model->addAll($commission_list);
            $wechat = new \Common\WeChat\Wechat();  //实例wechat类 消息提醒会员佣金分红

            foreach ($commission_list as $item) {

                $user_id = $item['user_id'];
                $customer_id = $item['customer_id'];
                
                $commission = $item['commission'];
                $member_model->where(array('id' => $user_id))->setInc('distribution_money', $commission); //累加会员分佣金额
         
                $member_info = get_user_info_wechat($user_id); //获取分佣会员信息
             
                $content = "好消息！！！您推荐的会员：[{$current_member['nickname']}],支付了一笔订单，您获得了相应的分红。"; //分佣消息提醒内容
                Log::write('下家消费啦'.$content);
                $wechat->sendMsg($member_info['openid'], $content);
                Log::write('消息发过啦'.$content);
            }

            if ($rows) {
                $dg_map['order_id'] = array('eq', $order['id']);
                $dg_map['order_no'] = array('eq', $order['order_no']);
                $dg_map['goods_id'] = array("in", $pids);

                $ordergoods_model->where($dg_map)->setField('commission_status', 1);
                $ordergoods_model->where($dg_map)->setField('commission_sacle', $assign_scale); //总佣金发放比例
                //echo M()->getLastSql();
                $this->_error = ("订单:" . $order['order_no'] . "---佣金已经发放：" . json_encode($commission_list));

                return TRUE;
            } else {
                $this->_error = ("佣金发放失败");
                return FALSE;
            }
        }
        return FALSE;
    }

}
